<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{

    public function getIndex(Request $request)
    {
        //每页显示条数
        $num = $request->input('num',15);

        //检测是否提交查询关键字
        if($request->has('keywords')){
            //分页查询 select * from user where username like '%admin%';
            $activitys = DB::table('activity')->where('title','like','%'.$request->input('keywords').'%')->paginate($num);
        }else{
            $activitys = DB::table('activity')->paginate($num);
        }

        //提取参数 分配到页面中
        $data = $request->except('page');


        //解析模板 分配数据
        return view('Admin.activity.index',['activitys'=>$activitys,'data'=>$data]);
    }
    //添加活动
    public function getAdd()
    {
        //查询已有的
        $activitys = DB::table('activity')->get();
        return view('Admin.activity.add',['activitys'=>$activitys]);
    }
    public function postInsert(Request $request)
    {
        //提取数据
        $data = $request->except('_token');

        //执行插入
        $res = DB::table('activity')->insert($data);

        if($res)
        {
            return redirect('/admin/activity/index')->with('success','分类添加成功');
        }else{
            return back()->with('error','分类添加失败');
        }
    }
    public function getEdit($id)
    {
        //根据id查询
        $activitys = DB::table('activity')->where('id',$id)->first();

        //解析模板 分配数据
        return view('Admin.activity.edit',['activitys'=>$activitys]);
    }
    //执行活动的修改
    public function postUpdate(Request $request)
    {
        //获取数据
        $data = $request->except('_token');
        //dd($data);
        //执行数据修改
        $res = DB::table('activity')->where('id',$data['id'])->update($data);


       if($res) {
           //重定向到activity/index
           return redirect('admin/activity/index')->with('success', '活动修改成功');
       }else{
           //回到上个页面
           return back()->with('error','活动修改失败');
       }
    }
    //执行活动的删除
    public function postDel(Request $request)
    {
        //获取数据
        $id = $request->input('id');

        //执行删除
        $res = DB::table('activity')->where('id',$id)->delete();

        echo $res;
    }
}

